<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        canvas {
            background-color: rgb(162, 150, 150);
        }
    </style>
</head>

<body>
    <canvas width="200" height="100"></canvas>
    <input type="text">

    <script>
        let canvas = document.getElementsByTagName("canvas")[0];
        let input = document.getElementsByTagName("input")[0];
        let context = canvas.getContext("2d");
        let newStr="";//用于保存验证码内容

        let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        let fontArr = ["微软雅黑", "宋体", "黑体"];

        function randomNumber(min, max) {
            let index = parseInt(Math.random() * (max - min + 1) + min);
            return index
        }

        // 1.随机数字或者字母（不分大小写）
        // 2.随机线条
        // 颜色随机、位置随机、大小长度随机
        canvas.onclick = function () {
            rander();

        }

        input.onblur=function(){
            // 获取用户输入的内容
            let word=input.value;
            if(word.toUpperCase===newStr.toUpperCase){
                alert("验证成功！");
            }else{
                alert("验证失败！请重新输入验证码！");
                rander();
                input.value="";
            }

        }

        rander();
        function rander() {
            // 清空画布
            context.clearRect(0,0,200,100);
            newStr="";
            // 绘制文本
            let x = 20;
            for (let i = 0; i < 4; i++) {
                context.beginPath();
                let text = str[randomNumber(0, str.length - 1)];
                let y = randomNumber(20, 80);
                let size = randomNumber(20, 40);
                context.fillStyle = `rgb(${randomNumber(0,255)},${randomNumber(0,255)},${randomNumber(0,255)})`;
                context.font = `${size}px ${fontArr[randomNumber(0,2)]}`;
                context.closePath();
                context.fillText(text, x, y);
                x += 30;
                newStr+=text;
            }

            console.log(newStr);
            // 绘制线条
            for (let i = 0; i < 5; i++) {
                context.beginPath();
                context.moveTo(randomNumber(0, 200), randomNumber(0, 100));
                context.lineTo(randomNumber(0, 200), randomNumber(0, 100));
                context.closePath();
                context.strokeStyle = `rgb(${randomNumber(0,255)},${randomNumber(0,255)},${randomNumber(0,255)})`;
                context.lineWidth = randomNumber(2, 6);
                context.stroke();
            }

        }
    </script>

</body>

</html>